package com.tutor.lzm.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tutor.lzm.R;
import com.tutor.lzm.entity.ValidateCodeEntity;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.request.RegisterRequest;
import com.tutor.lzm.http.request.SendValidateCodeRequest;
import com.tutor.lzm.entity.EmptyAppEntity;
import com.tutor.syslib.util.MessageTools;
import com.tutor.syslib.util.TextUtil;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by zzgpc on 2017-9-10.
 * 注册
 */
public class RegisterActivity extends BaseActivity {
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_password_again)
    EditText etPasswordAgain;
    @BindView(R.id.et_verification_code)
    EditText etVerificationCode;
    @BindView(R.id.tv_verification_code_get)
    TextView tvVerificationCodeGet;
    @BindView(R.id.btn_register)
    Button btnRegister;
    Unbinder unbinder;

    private Timer timer;// 计时器
    private int count = 60;// 记录时间，短信验证60秒内不能再次发送
    private String verificationCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        unbinder = ButterKnife.bind(this);
        initTitle("注册");
    }


    /**
     * 获取短信验证码
     */
    private void getValidateCode() {
        int ecolor = Color.RED; // whatever color you want
        String estring = "";
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        String phone = etMobile.getText().toString().trim();
        if (TextUtil.isNull(phone)) {
            estring = "请输入手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etMobile.setError(ssbuilder);
            return;
        }
        if (!TextUtil.isMobile(phone)) {
            estring = "请输入正确的手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etMobile.setError(ssbuilder);
            return;
        }
        count = 60;
        tvVerificationCodeGet.setEnabled(false);
        tvVerificationCodeGet.setTextColor(Color.parseColor("#949494"));
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(count--);
            }
        }, 0, 1000);

        SendValidateCodeRequest request = new SendValidateCodeRequest();
        request.phone = phone;

        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                ValidateCodeEntity.ValidateCode entity = (ValidateCodeEntity.ValidateCode) response;
                MessageTools.showToast(getApplicationContext(), "短信验证码发送成功");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(getApplicationContext(), msg);
            }
        });


    }


    /**
     * 注册
     */
    private void submitRegister() {
        verificationCode = etVerificationCode.getText().toString().trim();
        if (checkRequires()) {
            String phone = etMobile.getText().toString().trim();
            String nickName = etNickname.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            RegisterRequest request = new RegisterRequest();
            request.loginName = phone;
            request.password = password;
            request.nickName = nickName;
            request.captchaNum = verificationCode;

            HttpClient.post(request, new HttpClient.onSuccessListener() {
                @Override
                public void onSuccess(BaseResponse response) {
                    MessageTools.showToast(RegisterActivity.this, "注册成功");
                    finish();
                }
            }, new HttpClient.onFailListener() {
                @Override
                public void onFail(int code, String msg) {
                    MessageTools.showToast(RegisterActivity.this, msg);
                }
            });
        }
    }


    /**
     * 拼写检测，检测输入内容是否合乎要求
     */
    public boolean checkRequires() {
        int ecolor = Color.RED; // whatever color you want
        String estring = "";
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        if (TextUtil.isNull(etMobile.getText().toString().trim())) {
            estring = "请输入手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etMobile.setError(ssbuilder);
            return false;
        }
        if (!TextUtil.isMobile(etMobile.getText().toString().trim())) {
            estring = "请输入正确的手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etMobile.setError(ssbuilder);
            return false;
        }
//        if (StringUtil.isEmpty(etVerifyCode.getText().toString().trim())) {
//            estring = "请输入验证码";
//            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
//            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
//            etVerifyCode.setError(ssbuilder);
//            return false;
//        }
        String password = etPassword.getText().toString().trim();
        String passwordAgain = etPasswordAgain.getText().toString().trim();
        if (TextUtil.isNull(password)) {
            estring = "请输入密码";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etPassword.setError(ssbuilder);
            return false;
        }
        if (password.length() < 6 || password.length() > 12) {
            MessageTools.showToast(this, "密码应该在6—12位");
            return false;
        }
        if (!password.equals(passwordAgain)) {
            estring = "两次密码输入不一致";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etPasswordAgain.setError(ssbuilder);
            return false;
        }

        String code = etVerificationCode.getText().toString().trim();
        if (TextUtil.isNull(code)) {
            MessageTools.showToast(oThis, "请输入短信验证码");
            return false;
        }
        if (!verificationCode.equals(code)) {
            MessageTools.showToast(oThis, "验证码错误");
            return false;
        }

        return true;
    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                timer.cancel();
                if (tvVerificationCodeGet != null) {
                    tvVerificationCodeGet.setEnabled(true);
                    tvVerificationCodeGet.setTextColor(getResources().getColor(R.color.text_pink2));
                    tvVerificationCodeGet.setText("获取");
                }
            } else {
                if (tvVerificationCodeGet != null) {
                    tvVerificationCodeGet.setText(msg.what + "秒");
                }
            }
        }

        ;

    };

    @OnClick({R.id.tv_verification_code_get, R.id.btn_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_verification_code_get:
                //获取短信验证码
                getValidateCode();
                break;
            case R.id.btn_register:
                //注册
                submitRegister();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
